package Demo1;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class modifyServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
         resp.setContentType("text/html;charset=UTF-8");


         // 获取表单中已经修改过的数据
        String deptno = req.getParameter("deptno");
        String dname = req.getParameter("dname");
        String loc = req.getParameter("loc");

        int count = 0;
        // 获取数据库中的数据并将对应的值进行修改
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        String sql = "update dept set dname =?,loc = ? where deptno = ?";

        try {
            connection = DBUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,dname);
            preparedStatement.setString(2,loc);
            preparedStatement.setString(3,deptno);
            count = preparedStatement.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,preparedStatement,null);
        }
        // 检测是否修改成功
        if(count==1){
            // 成功
//            req.getRequestDispatcher("/dept/list").forward(req,resp);

            // 使用重定向的方式.
            resp.sendRedirect(req.getContextPath()+"/dept/list");
        }else{
            // 失败
//            req.getRequestDispatcher("/Modifyerror.html").forward(req,resp);

            resp.sendRedirect(req.getContextPath()+"/Modifyerror.html");
        }

    }
}
